#[path= "../util/result.rs"]
mod result;
#[path= "../entity/user.rs"]
mod user;
use actix_web::{post, web, HttpResponse};
use sqlx::MySqlPool;
use user::UserEntity;
use result::Rest;

#[derive(serde::Deserialize)]
pub struct LoginData {
    username: String,
    password: String,
}

#[post("/login")]
pub async fn login(pool: web::Data<MySqlPool>, login_data: web::Query<LoginData>) -> HttpResponse {
    // 添加日志输出，检查请求体是否被正确解析
    log::debug!("Received login request: username={}, password={}", login_data.username, login_data.password);

    match sqlx::query_as::<_, UserEntity>("SELECT id, name, gender, birth_date, entry_date, employment_status, unit_name, unit_code, education, highest_degree FROM art_college_teachers WHERE id = ? ")
        .bind(&login_data.username)
        .fetch_one(&**pool)
        .await
    {
        Ok(user) => {
            // 生成 token，这里简单使用用户工号作为 token
            let token = user.id.to_string();
            log::info!("Login successful for user: {}", user.id); // 添加成功日志
            HttpResponse::Ok().json(Rest::ok(token))
        },
        Err(e) => {
            log::error!("Login failed for user: {}, error: {}", login_data.username, e); // 添加失败日志
            HttpResponse::Unauthorized().json(Rest::<()>::err(format!("Invalid username or password: {}", e)))
        },
    }
}